package api

import (
	"errors"
	"log"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type SqliteDB struct {
	connection *gorm.DB
}

func newSqliteDB(path string) *SqliteDB {
	sqlitedb := &SqliteDB{}
	db, error := gorm.Open(sqlite.Open(path), &gorm.Config{})
	if error != nil {
		panic("failed to connect sqlite db")
	}
	sqlitedb.connection = db
	return sqlitedb
}

func (_this *SqliteDB) GetConnection() *gorm.DB {
	if _this.connection == nil {
		return nil
	}
	return _this.connection
}

func GetdbInstance(path string) *SqliteDB {
	if path == "" {
		log.Fatal("path is nil")
		return nil
	}
	return newSqliteDB(path)
}

func (_this *SqliteDB) Transaction(callback func(db *gorm.DB)) error {
	if callback == nil {
		log.Fatal("callback is nil")
		return errors.New("Transaction error")
	}
	tx := _this.connection.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if error := tx.Error; error != nil {
		return error
	}
	callback(tx)
	error := tx.Commit().Error
	if error != nil {
		return errors.New("Transaction error")
	}
	return nil
}
